import axios from 'axios'
import { Loading, Message, Notification } from 'element-ui'
// import router from '@/router'
const request = axios.create({
  // baseURL: 'http://192.168.1.107:8080/typing_game'
  baseURL: 'http://159.75.251.43:8080'
  // baseURL: 'http://192.168.111.216:8080/typing_game'
})
axios.defaults.withCredentials = true
// axios.defaults.headers['Access-Control-Allow-Methods'] = 'DELETE'
let loadingInstance = null
// 配置请求拦截器
request.interceptors.request.use(
  (config) => {
    // 声明token认证字段 这里的认证字段是 tag已经存在所以不再认证
    // config.headers.Authorization = 'Bearer xxx'

    // 开启loding效果
    loadingInstance = Loading.service({
      fullscreen: true,
      text: '正在努力加载中'
    })
    return config
  },
  (error) => {
    loadingInstance.close()
    Message.error({
      message: '加载超时'
    })
    return Promise.reject(error)
  }
)

// 配置响应拦截器
request.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.code === 506) {
      console.log('ok')
      localStorage.removeItem('username')
      localStorage.removeItem('mobilePhone')
      localStorage.removeItem('tag')
      Message({
        showClose: true,
        message: '登录失效,请重新登录',
        type: 'error'
      })
      // Notification({
      //   title: '提示',
      //   message: '登录失效,请重新登录',
      //   duration: 0
      // })
      setTimeout(() => {
        window.location.href = '/login'
      }, 2000)
    }
    // 关闭loading效果 // 以服务的方式调用的 Loading 需要异步关闭
    loadingInstance.close()
    return response
  },
  (error) => {
    loadingInstance.close()
    Message.error({
      message: '加载失败'
    })
    return Promise.reject(error)
  }
)
export default request
